package com.ndood.payment.core.utils;

import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;

import com.ndood.core.utils.Md5Util;

public class Sha1Util {
	
	public static String SHA1(String decript) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			digest.update(decript.getBytes("UTF-8"));
			byte[] messageDigest = digest.digest();
			StringBuilder hexString = new StringBuilder();
			for (byte message : messageDigest) {
				String shaHex = Integer.toHexString(message & 0xFF);
				if (shaHex.length() < 2)
					hexString.append(0);

				hexString.append(shaHex);
			}
			return hexString.toString().toLowerCase();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	// 排序
	public static String sort(Map<String, Object> paramMap) throws Exception {
		String sort = "";
		MapUtil signMap = new MapUtil();
		if (paramMap != null) {
			String key;
			for (Iterator<String> it = paramMap.keySet().iterator(); it.hasNext();) {
				key = (String) it.next();
				String value = ((paramMap.get(key) != null) && (!("".equals(paramMap.get(key).toString()))))
						? paramMap.get(key).toString()
						: "";
				signMap.put(key, value);
			}
			signMap.sort();
			for (Iterator<String> it = signMap.keySet().iterator(); it.hasNext();) {
				key = (String) it.next();
				sort = sort + key + "=" + signMap.get(key).toString() + "&";
			}
			if ((sort != null) && (!("".equals(sort)))) {
				sort = sort.substring(0, sort.length() - 1);
			}
		}
		return sort;
	}
	
	/**
     * 签名
     */
    public static String sign(Map<String, Object> postMap) {
        String sortStr = null;
        String sign    = null;
        try {
            /**
             * 1 A~z排序(加上key)
             */
            sortStr = sort(postMap);
            /**
             * 2 sha1加密(小写)
             */
            String sha1 = Sha1Util.SHA1(sortStr);
            /**
             * 3 md5加密(小写)
             */
            sign = Md5Util.md5Encode(sha1).toLowerCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }
    
    /**
     * 验签
     * @param respObject
     * @return
     */
    public static Boolean verifySign(Map<String,Object> postMap,String key) {
        String respSign = postMap.get("sign").toString();
        postMap.remove("sign");
        postMap.put("key", key);
        // 按A~z排序，串联成字符串，先进行sha1加密(小写)，再进行md5加密(小写)，得到签名
        String veriSign = sign(postMap);    
        if (respSign.equals(veriSign)) {
            return true;
        } else {
            return false;
        }
    }
}